package juc;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者消费者
 * 使用blockingQueue volatile
 */
class ShareResource {
    private volatile boolean flag = true;//生产与消息开启
    private AtomicInteger ai = new AtomicInteger();

    BlockingQueue<String> blockingQueue = null;

    public ShareResource(BlockingQueue<String> blockingQueue){
        this.blockingQueue = blockingQueue;
        System.out.println(">>>>"+blockingQueue.getClass().getName());
    }

    public void product() throws Exception {
        String data = null;
        boolean value;
        while (flag){
            data = ai.incrementAndGet()+"";
            value = blockingQueue.offer(data,2l, TimeUnit.SECONDS);
            if(value){
                System.out.println(Thread.currentThread().getName()+">>插入成功");
            }else{
                System.out.println(Thread.currentThread().getName()+">>插入失败");
            }
            TimeUnit.SECONDS.sleep(1l);
        }

        System.out.println(Thread.currentThread().getName()+">>停止");
    }

    public void consumer() throws Exception {
        String result = null;
        while(flag){
            result = blockingQueue.poll(2l,TimeUnit.SECONDS);
            if(null == result ){
                flag = false;// 没有取到，则停止
                System.out.println("没有获取到，自动停止");
                return;
            }
            System.out.println(Thread.currentThread().getName()+".. 消费"+result);
        }
    }

    public void stop(){
        flag = false;
    }
}
public class CASBlockingQueue {
    public static void main(String[] args) {
        ShareResource resource = new ShareResource(new ArrayBlockingQueue<String>(10));
        new Thread(()->{
            try {
                resource.product();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"product:").start();

        new Thread(()->{
            try {
                resource.consumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"consomer:").start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println();
        resource.stop();
        System.out.println("主动停止");
    }
}
